<template>
  <div class="upload-demo">
    <div class="avatar-upload">
      <!-- Element Plus 上传组件 -->
      <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeUpload"
        :http-request="handleUpload">
        <!-- 显示上传的头像或默认图标 -->
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>

      <!-- 上传提示 -->
      <div v-if="!imageUrl" class="upload-tip">点击上传头像</div>

      <!-- 上传进度条 -->
      <el-progress v-if="uploading" :percentage="progressPercent" :status="progressStatus" :stroke-width="16"
        class="upload-progress"></el-progress>

      <!-- 错误提示 -->
      <el-alert v-if="errorMessage" :title="errorMessage" type="error" show-icon @close="errorMessage = ''"></el-alert>
    </div>
  </div>
</template>

<script>
import { getUploadTokens, uploadImage } from '@/utils/helloImgUpload.js' // 导入 API 方法
import { showMsg } from '@/utils/showMsg.js'
const { config } = require('../../../config')

export default {
  data()
  {
    return {
      imageUrl: '', // 上传成功后的图片 URL
      uploading: false, // 是否正在上传
      progressPercent: 0, // 上传进度百分比
      progressStatus: '', // 进度条状态（空表示默认状态）
      errorMessage: '', // 错误信息
      progressInterval: null // 用于存储进度条定时器
    }
  },
  methods: {
    // 上传前的校验
    beforeUpload(file)
    {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage)
      {
        showMsg('错误', '只能上传图片文件！', 'error')
        return false
      }
      if (!isLt2M)
      {
        showMsg('错误', '图片大小不能超过 2MB！', 'error')
        return false
      }

      return true
    },

    // 模拟进度条
    startFakeProgress()
    {
      this.progressPercent = 0
      this.progressInterval = setInterval(() =>
      {
        if (this.progressPercent < 99)

          this.progressPercent += 1 // 每秒增加 1%
      }, 30) // 30ms 更新一次，3 秒内从 0% 到 99%
    },

    // 停止模拟进度条
    stopFakeProgress()
    {
      if (this.progressInterval)
      {
        clearInterval(this.progressInterval)
        this.progressInterval = null
      }
    },

    // 自定义上传逻辑
    async handleUpload(options)
    {
      const { file } = options

      try
      {
        this.uploading = true
        this.progressStatus = '' // 初始状态为空

        // 启动模拟进度条
        this.startFakeProgress()

        // 1. 获取临时上传 Token
        const tokens = await getUploadTokens()
        const uploadToken = tokens[0].token

        // 2. 上传图片
        const formData = new FormData()
        formData.append('file', file)
        formData.append('token', uploadToken)
        formData.append('permission', 1) // 默认公开

        const uploadResponse = await uploadImage(config.helloToken, file, uploadToken, {
          permission: 1 // 默认公开
        })

        // 3. 停止模拟进度条，并设置为 100%
        this.stopFakeProgress()
        this.progressPercent = 100

        // 4. 更新图片 URL
        this.imageUrl = uploadResponse.links.url
        showMsg('成功', '头像上传成功！', 'success')
        this.progressStatus = 'success' // 上传完成后设置为成功状态

        // 5. 触发自定义事件，将 imageUrl 传递给父组件
        this.$emit('upload-success', this.imageUrl)

        // 6. 延迟隐藏进度条
        setTimeout(() =>
        {
          this.uploading = false
        }, 500) // 0.5 秒后隐藏进度条
      }
      catch (error)
      {
        this.stopFakeProgress() // 停止模拟进度条
        this.errorMessage = error.message || '上传失败，请重试！'
        this.progressStatus = 'exception' // 上传失败时设置为异常状态
      }
    }
  }
}
</script>

<style scoped>
.upload-demo {
  width: 200px;
}

.avatar-upload {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column nowrap;
}

.avatar-uploader {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader .el-upload {
  border: 2px solid #000000;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.avatar {
  width: 152px;
  height: 152px;
  display: block;
  border-radius: 50%;
}

.upload-tip {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}

.upload-progress {
  width: 150px;
  margin: 5px 0px 5px 50px;
}
</style>
